var memberUtil=require('../../../utils/memberUtil');
var util = require('../../../utils/shareUtil.js');
var app = getApp();
Page({
  data: {
    items: [],
    likes: [],
    jifenItems:[],
    //购物车是否为空
    empty:0,
    kongcar:0,
    //合计
    count:0,
    //全选
    SelectAll:false,
    Address:{},
    startX: 0, //开始坐标
    startY: 0,
    // tab 切换
    tabArr: {
      curHdIndex: 0,
      curBdIndex: 0
    },
    imagesUrl: app.globalData.baseImageUrl,
    serverImageUrl:app.globalData.baseUrl,
    userInfo:null,
    belongto:0,
    isWx:true,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
      isExistAddress:false
  },
  //tab切换
  tab: function (e) {

    var dataId = e.currentTarget.id;
    var belongto= e.currentTarget.dataset.belongto;
    var obj = {};
    obj.curHdIndex = dataId;
    obj.curBdIndex = dataId;
    this.setData({
      tabArr:obj,
      belongto:belongto,
      count:0,
      SelectAll:false
    })
    this.getCarList(belongto);
  },
 //全选
  bindSelectAll:function(e){
     console.log(e);
    var that = this;
    var select = !that.data.SelectAll;
    var items=null;
    console.log(select);

    if(that.data.belongto==0){//商城
      items=that.data.items;
    }else{
      //积分
      items=that.data.jifenItems;
    }
    if (select){
      if(items.length>0) {
        that.setData({
          empty:1
        })
        for (var i in items) {
          items[i].checked = "true";
        }
        if (that.data.belongto == 0) {//商城
          that.setData({
            items: items,
            SelectAll: true
          })
        } else {
          //积分
          that.setData({
            jifenItems: items,
            SelectAll: true
          })
        }
      }else{
        that.setData({
          SelectAll: false,
          empty:0
        })
        wx.showModal({
          title: '请先添加商品到购物车',
          showCancel: false
        })
        return false;
      }

     }else{
      if(items.length>0) {
        that.setData({
          empty:0
        })
        for (var i in items) {
          items[i].checked = "";
        }
        if (that.data.belongto == 0) {//商城
          that.setData({
            items: items,
            SelectAll: false
          })
        } else {
          //积分
          that.setData({
            jifenItems: items,
            SelectAll: false
          })
        }
      }else{
        that.setData({
          SelectAll: false,
          empty:1
        })
        wx.showModal({
          title: '请先添加商品到购物车',
          showCancel: false
        })
        return false;
      }
     }
     that.count();
  },
  //选择
  checkChange: function (e) {
    var that=this;
    console.log(e);
    var index=e.currentTarget.dataset.index;
    var items=null;
    if(that.data.belongto==0){
      //商城
      items=that.data.items;
    }else{
      //积分
      items=that.data.jifenItems;
    }
    if(items.length>0) {
      if (items[index].checked == "true") {
        items[index].checked = "";
      } else {
        items[index].checked = "true";
      }

      if (that.data.belongto == 0) {
        //商城
        that.setData({
          items: items
        })
      } else {
        //积分
        that.setData({
          jifenItems: items
        })
      }

      var a = 0;
      for (var i in items) {
        if (items[i].checked == "true") {
          a++
        }
      }
      if (a == items.length) {
        that.setData({
          SelectAll: true,
          empty: 1
        })
      } else {
        if (a > 0) {
          that.setData({
            empty: 1
          })
        } else {
          that.setData({
            empty: 0
          })
        }
        that.setData({
          SelectAll: false
        })
      }
      that.count();
    }else{
      wx.showModal({
        title: '请先添加商品到购物车',
        showCancel: false
      })
      return false;
    }
  },
  //结算
  bindBuyStore: function(){
    var that=this;
    if (this.data.tabArr.curHdIndex == 0){//商城
      if(that.data.items.length>0){
      if(that.data.empty==0){
          wx.showModal({
            title: '请先选择商品到购物车',
            showCancel: false
          })
        return false;
        }
      }else{
        if(that.data.kongcar==0){
          wx.showModal({
            title: '请先添加商品到购物车',
            showCancel: false
          })
          return false;
        }
      }
      this.storeCar()
    }else{//积分
      if(that.data.items.length>0){
        if(that.data.empty==0){
          wx.showModal({
            title: '请先选择商品到购物车',
            showCancel: false
          })
          return false;
        }
      }else{
        if(that.data.kongcar==0){
          wx.showModal({
            title: '请先添加商品到购物车',
            showCancel: false
          })
          return false;
        }
      }
      this.scoreCar()
    }
  },
  onLoad: function () {
    var that = this;
    var res=(wx.getStorageSync("loginUserInfo").userInfo==undefined?"":wx.getStorageSync("loginUserInfo").userInfo);
    that.setData({
      userInfo:res
    })
    if(that.data.userInfo.id==undefined) {
      memberUtil.getLogin(app,0,1,that,2);
    }
     //wx.getSetting({
     //  success: function (res) {
     //    if (!res.authSetting['scope.userInfo']) {
     //      that.setData({
     //        isWx:false
     //      })
     //    }
     //  }
     //})

  },
  //起始坐标
  touchstart: function (e) {
this.setData({
startX: e.changedTouches[0].clientX,
startY: e.changedTouches[0].clientY
})
  },
  //滑动过程
  touchmove:function(e){
    var that = this;
    console.log(e)
    var index = e.currentTarget.dataset.index,//当前索引
      startX = that.data.startX,//开始X坐标
      startY = that.data.startY,//开始Y坐标
      touchMoveX = e.changedTouches[0].clientX,//滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY;//滑动变化坐标
      
    //获取滑动角度
    var angle = that.angle({ X: startX, Y: startY }, { X: touchMoveX, Y: touchMoveY });
    if (Math.abs(angle) > 30) return;
    
    if (that.data.belongto==0){
      if (touchMoveX > startX) {//右滑
        that.data.items[index].isTouchMove = false;
      } else { //左滑
        that.data.items[index].isTouchMove = true;
      }
        this.setData({
          items: that.data.items
        })
      }else{
      if (touchMoveX > startX) {//右滑
        that.data.jifenItems[index].isTouchMove = false;
      } else { //左滑
        that.data.jifenItems[index].isTouchMove = true;
      }
      this.setData({
        jifenItems: that.data.jifenItems
      })
      }
    
  },
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  //删除商品
  bindDel:function(e){
    var that=this;
    var index=e.currentTarget.dataset.id;
    var goodsId=e.currentTarget.dataset.orderid;
    var items=null;
    if(that.data.belongto==0){
      items=that.data.items;
    }else{
      items=that.data.jifenItems;
    }

    if (items.length == 0) {
      that.setData({
        empty: 1
      })
    }
    var shoppingCartItemIdJson={
      shoppingCartItemId:goodsId
    }
    wx.request({
      url: app.globalData.baseUrl + '/shoppingCartItem/deleteShoppingCartItem',
      method: 'POST',
      data: JSON.stringify(shoppingCartItemIdJson),
      success: function (res) {
        if(res.data.status==200) {
          wx.showToast({
            title: '商品删除成功',
            icon: 'none',
            duration: 1000
          })
          that.onLoad();
          that.onShow();
          that.count()
        }
      }
    })
    
  },
  //你可能喜欢
  getLike: function (){
    var that=this;
    //获取地址
    wx.request({
      url: app.globalData.baseUrl+'/goods/mayBeLike',
      header: app.globalData.headerPost,
      method: 'GET',
      success:function(res){
        var likeObj="";
        if(res.data.length>0) {
          that.setData({
            likes: res.data
          })
        }

      }
    })
  },

  //获取地址
  getAddress: function (){
    var that=this;
    var json={memberId:this.data.userInfo.id}
    //获取地址
    wx.request({
      url: app.globalData.baseUrl+'/member/receivingAddress/findReceivingAddressByMemberId',
      header: app.globalData.headerPost,
      method: 'POST',
      data:JSON.stringify(json),
      success:function(res){
        var addressObj="";
        var isExistAddress=false;
        if(Number(res.data.length)>0) {
          addressObj=res.data[0];
            isExistAddress=true;
        }
        that.setData({
          address: addressObj,
            isExistAddress:isExistAddress
        })
      }
    })
  },
  //减法
  bindReduce:function(e){
    var that=this;
   console.log(e);
    var index = parseInt(e.currentTarget.dataset.index);
    var num = 0;//数量
    var items=null;
    var totalPrice=0;
    console.log(num);
   if(that.data.belongto==0){
     //商城
     items=that.data.items;
   }else{
     //积分
     items=that.data.jifenItems;
   }
    num = Number(items[index].buyNumber);//数量
      if (num > 1) {
        num--;
        items[index].buyNumber = num;

        if(that.data.belongto==0){
          totalPrice=Number(items[index].goodsPrice)*num;
          items[index].totalPrice=totalPrice;
          items[index].totalConsumerMoney=totalPrice;
          //商城
          that.setData({
            items:items
          });
        }else{
          //积分
          totalPrice=Number(items[index].goodsIntegral)*num;
          items[index].totalIntegral=totalPrice;
          items[index].totalPrice=totalPrice;
          items[index].totalConsumerMoney=totalPrice;
          that.setData({
            jifenItems: items
          });
        }

      //}
      that.count();
        that.numChange(items[index])
    }

  },
  //加法
  bindAdd: function (e) {
    var that=this;
    var index = parseInt(e.currentTarget.dataset.index);
    var num = 0;
    var items=null;
    var totalPrice=0;
    if(that.data.belongto==0){
      //商城积分
      items=that.data.items;
    }else{
      //积分商城
      items=that.data.jifenItems;
    }
    num = Number(items[index].buyNumber);
    
    //var callback=function(){
      if (num >= 0) {
        num++;
        items[index].buyNumber = num;
        if(that.data.belongto==0){
          totalPrice=Number(items[index].goodsPrice)*num;
          items[index].totalPrice=totalPrice;
          items[index].totalConsumerMoney=totalPrice;
          //商城积分
          that.setData({
            items: items
          });
        }else{
          totalPrice=Number(items[index].goodsIntegral)*num;
          items[index].totalIntegral=totalPrice;
          items[index].totalPrice=totalPrice;
          items[index].totalConsumerMoney=totalPrice;
          //积分商城
          that.setData({
            jifenItems: items
          });
        }
        that.count();
        that.numChange(items[index]);
      }

    //}

  },
  //获取购物列表
  getCarList: function (belongto) {
    var that=this;
    var gouwuche=1;
    var shoppingCartParamJson = {
      memberId:that.data.userInfo.id,
      belongTo:belongto
    }
    //获取购物车列表
    wx.request({
      url: app.globalData.baseUrl + '/shoppingCartItem/findShoppingCartItemList',
      method: 'POST',
      data:JSON.stringify(shoppingCartParamJson),
      success: function (res) {
        console.log(res.data)
        var itemObjList=[];
        if(Number(res.data.length)>=1){
          itemObjList=res.data;
        }
        if(itemObjList.length==0){
          gouwuche=0;
        }
        if(belongto==0){
          //商城购物车
          that.setData({
            items:itemObjList,
            kongcar:gouwuche,
            empty:0,
            tabArr: {
              curHdIndex: 0,
              curBdIndex: 0
            },
            SelectAll: false,
            count:0,
            belongto:belongto
          })
        }else{
          //积分购物车
          that.setData({
            kongcar:gouwuche,
            jifenItems:itemObjList,
            empty:0,
            tabArr: {
              curHdIndex: 1,
              curBdIndex: 1
            },
            SelectAll: false,
            count:0,
            belongto:belongto
          })
        }

      }
    })
  },
  //总计
  count:function(){
    var that=this;
    var count = 0;
    var items =null;
    if(that.data.belongto==0){//商城
      items = this.data.items;
      for (var i = 0; i < items.length; i++) {
        if (items[i].checked){
          count = Number(Number(count)+Number(items[i].goodsPrice) * Number(items[i].buyNumber)).toFixed(2);
        }
      }
    }else{
      //积分
      items = this.data.jifenItems;
      for (var i = 0; i < items.length; i++) {
        if (items[i].checked){
          count = Number(Number(count)+Number(items[i].goodsIntegral) * Number(items[i].buyNumber)).toFixed(2);
        }
      }
    }
    this.setData({
      count: count
    })
  },
  //商品购物车结算
  storeCar:function(){
    var that=this;
    if(!that.data.isExistAddress){
        wx.showModal({
            title: '您还没有添加收货地址哦,赶紧去添加收货地址吧？',
            content: '',
            success: function (res) {
                if (res.confirm) {
                    wx.navigateTo({
                        url: '/pages/my/address?type=add'
                    })
                }
            }
        });
      return false;
    }
    var totalPric=Number(that.data.count);
    var goodsPicUrl="";
      var yunfei=0;
      if(totalPric<199){
          yunfei=10;
      }
    var orderParamJson={
      memberId: that.data.userInfo.id,
      receivingAddressId:that.data.address.id,
      paymentConsumerMoney:totalPric,
      //buyerMessage:"麻烦尽快发货",
      buyerNickname:that.data.address.receiverName,
      orderDetailParamList:[],
        expressFee:yunfei
    }
    for(var i in that.data.items){
      if(that.data.items[i].checked){
        orderParamJson.orderDetailParamList.push({
          goodsId: that.data.items[i].goodsId,
          memberId:  that.data.userInfo.id,
          shoppingCartItemId:that.data.items[i].id,
          goodsSpecificationId:that.data.items[i].goodsSpecificationId,
          isSpecificationGoods:that.data.items[i].isSpecificationGoods,
          specificationName:that.data.items[i].specificationName,
          buyNumber:that.data.items[i].buyNumber,
          goodsName: that.data.items[i].goodsName,
          goodsPrice: that.data.items[i].goodsPrice,
          totalConsumerMoney: that.data.items[i].totalPrice,
          goodsPicUrl:that.data.items[i].goodsPicUrl
        })
        goodsPicUrl=that.data.items[i].goodsPicUrl;
      }
    }
    orderParamJson.goodsPicUrl=goodsPicUrl;
    wx.request({
      url: app.globalData.baseUrl + '/order/createOrder',
      data: JSON.stringify(orderParamJson),
      method: 'POST',
      success: function (res) {
        if(res.data.status==200){
          var items=[];
          for(var i in that.data.items){
            if(!that.data.items[i].checked){
              items.push(that.data.items[i]);
            }
          }
          that.setData({
            items:items
          })

          that.count();
          wx.navigateTo({
            url: '/pages/shopcar/buy?belongTo=0'+"&totalPrice="+(totalPric+Number(yunfei))+"&orderId="+res.data.data.orderId+"&orderNumber="+res.data.data.orderNumber+"&goodsname="+orderParamJson.orderDetailParamList[0].goodsName
          })
        }
      }
    })
  },
  //积分购物车结算
  scoreCar:function(){
    var that=this;
      if(!that.data.isExistAddress){
          wx.showModal({
              title: '您还没有添加收货地址哦,赶紧去添加收货地址吧？',
              content: '',
              success: function (res) {
                  if (res.confirm) {
                      wx.navigateTo({
                          url: '/pages/my/address?type=add'
                      })
                  }
              }
          });
          return false;
      }
    var totalPric=Number(that.data.count);
    var goodsPicUrl="";
    var yunfei=0;
    if(totalPric<199){
      yunfei=10;
    }
    var integralOrderParamJson={
      memberId: that.data.userInfo.id,
      receivingAddressId:that.data.address.id,
      paymentIntegral:totalPric,
      //buyerMessage:"麻烦尽快发货",
      buyerNickname:that.data.address.receiverName,
      integralOrderDetailParamList:[],
        expressFee:yunfei
    }
    for(var i in that.data.jifenItems){
      if(that.data.jifenItems[i].checked){
        integralOrderParamJson.integralOrderDetailParamList.push({
          goodsId: that.data.jifenItems[i].goodsId,
          memberId: that.data.userInfo.id,
          shoppingCartItemId:that.data.jifenItems[i].id,
          goodsSpecificationId:that.data.jifenItems[i].goodsSpecificationId,
          isSpecificationGoods:that.data.jifenItems[i].isSpecificationGoods,
          specificationName:that.data.jifenItems[i].specificationName,
          buyNumber:that.data.jifenItems[i].buyNumber,
          goodsName: that.data.jifenItems[i].goodsName,
          goodsIntegral: that.data.jifenItems[i].goodsIntegral,
          totalIntegral: that.data.jifenItems[i].totalIntegral,
          goodsPicUrl:that.data.jifenItems[i].goodsPicUrl
        })
        goodsPicUrl=that.data.jifenItems[i].goodsPicUrl;
      }
    }
    integralOrderParamJson.goodsPicUrl=goodsPicUrl;
    wx.request({
      url: app.globalData.baseUrl + '/order/createIntegralOrder',
      method: 'POST',
      data: JSON.stringify(integralOrderParamJson),
      success: function (res) {
        console.log("积分购物车订单提交="+JSON.stringify(res.data))
        if (res.data.status==200) {
          var items=[];
          for(var i in that.data.jifenItems){
            if(!that.data.jifenItems[i].checked){
              items.push(that.data.jifenItems[i]);
            }
          }
          that.setData({
            jifenItems:items
          })

          that.count();
          wx.navigateTo({
            url: '/pages/shopcar/buy?belongTo=1'+"&totalPrice="+(totalPric+Number(yunfei))+"&orderId="+res.data.data.orderId+"&orderNumber="+res.data.data.orderNumber+"&goodsname="+integralOrderParamJson.integralOrderDetailParamList[0].goodsName
          })
        }
      }
    })
  },
  //商品数量改变
  numChange: function (obj){
    var that=this;
    if (that.data.tabArr.curHdIndex==0){//商城
      var goodsNumberUpdateParamJson={
        shoppingCartItemId:obj.id,
        buyNumber:obj.buyNumber,
        goodsPrice:obj.goodsPrice,
        goodsConsumerMoney:obj.goodsConsumerMoney,
        totalPrice:obj.totalPrice,
        totalConsumerMoney:obj.totalPrice
      }
      wx.request({
        url: app.globalData.baseUrl + '/shoppingCartItem/goodsNumberUpdate',
        method: 'POST',
        data: JSON.stringify(goodsNumberUpdateParamJson),
        success: function (res) {
        }
      })
    } else if (that.data.tabArr.curBdIndex == 1){//积分
      var integralGoodsNumberUpdateParamJson= {
        shoppingCartItemId: obj.id,
        buyNumber: obj.buyNumber,
        goodsIntegral: obj.goodsIntegral,
        goodsConsumerMoney: obj.goodsConsumerMoney,
        totalIntegral: obj.totalIntegral,
        totalConsumerMoney:  obj.totalPrice
      }
      wx.request({
        url: app.globalData.baseUrl + '/shoppingCartItem/integralGoodsNumberUpdate',
        method: 'POST',
        data: JSON.stringify(integralGoodsNumberUpdateParamJson),
        success: function (res) {
        }
      })
    }
    
  },
  //授权
  isWxShow:function() {
    var that=this;
    that.setData({
      isWx: !(that.data.isWx)
    })
  },
  //授权
  bindGetUserInfo:function(e){
    var that = this;
    wx.getSetting({
      success: function(res) {
        if (res.authSetting['scope.userInfo']) {
          app.getUserInfoM();
          that.setData({
            isWx: !(that.data.isWx)
          })
        } else {
          wx.hideLoading();
          wx.showToast({
            title: '用户拒绝授权',
            icon: 'none',
            duration: 1000
          })
        }
      }
    })
  },
  //页面跳转
  goodsDetailNavigate:function(e){
    wx.showLoading({
      title: '数据加载中',
      mask: true
    })
    var goodsId=e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/shop/shopDt?goodsId='+goodsId
    })
    wx.hideLoading();
  },
    //页面跳转
    goodsDetailNavigate:function(e){
        wx.showLoading({
            title: '数据加载中',
            mask: true
        })
        wx.hideLoading();
        var goodsId=e.currentTarget.dataset.id;
        wx.navigateTo({
            url: '/pages/shop/shopDt?goodsId='+goodsId
        })

    },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that=this;
    that.getAddress();//获取地址
    that.getCarList(0);//获取商品列表
    //that.count();//计算总价
    that.getLike();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that=this;
    return {
      title: '我的二维码',
      path: "/pages/shop/addressSearch?parentId=" + that.data.userInfo.id + "&enterType=0",
      imageUrl: app.globalData.loginUserInfo.erweimaUrl
    }
  }
})
  
